package cqgans.app.sunao.com.cqgans.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.lang.reflect.Method;

import cqgans.app.sunao.com.cqgans.bean.User;
import cqgans.app.sunao.com.cqgans.bean.VersionDataBean;
import cqgans.app.sunao.com.cqgans.common.AppConstant;
import cqgans.app.sunao.com.cqgans.ui.view.RegisterActivity;
import cqgans.app.sunao.com.cqgansnew.R;

import static cqgans.app.sunao.com.cqgans.common.AppConstant.isHomePage;
import static cqgans.app.sunao.com.cqgans.common.AppConstant.user;


@SuppressWarnings("WrongConstant")
@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    @ViewInject(R.id.login_username)
    EditText login_username;
    @ViewInject(R.id.login_password)
    EditText login_password;
    @ViewInject(R.id.login_button)
    Button login_button;
    @ViewInject(R.id.login_loading)
    RelativeLayout login_loading;
    private String name = "";
    private String password = "";
    @ViewInject(R.id.register_btn)
    TextView register_btn;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        sharedPreferences = getSharedPreferences("cqgas", Context.MODE_PRIVATE);
        autoLogin();
    }

    private void autoLogin() {
        ((TextView) this.findViewById(R.id.version)).setText("当前版本号：" + getAppVersionName(this));
        //版本更新,去服务器获取最新的版本,和本地版本比较
        upload();


    }
private void auto(){

    int id = sharedPreferences.getInt("id", 0);

    if (id != 0) {
        User muser = new User();
        muser.setId(id);
        muser.setMobile(sharedPreferences.getString("mobile", ""));
        muser.setUsername(sharedPreferences.getString("userName", ""));
        muser.setUserNumber(sharedPreferences.getString("userNumber", ""));
        user = muser;
        Toast.makeText(this, "自动登录成功", 1500).show();
        if (isHomePage) {
            startActivity(new Intent(MainActivity.this, OldHomeActivity.class));

        } else {
            startActivity(new Intent(MainActivity.this, Home2Activity.class));

        }
        finish();
    }
}
    @Override
    protected void onResume() {
        super.onResume();
        setTitleBar("安燃通", 1);
    }

    @Event(value = {R.id.login_button, R.id.register_btn})
    private void click(View view) {
        switch (view.getId()) {
            case R.id.login_button:
                login_loading.setVisibility(View.VISIBLE);
                //登录校验
                if (loginVerify()) {
                    login();
                } else {
                    login_loading.setVisibility(View.GONE);
                }
                break;
            case R.id.register_btn:
                startActivity(new Intent(MainActivity.this, RegisterActivity.class));
                break;
        }

    }

    @SuppressWarnings("WrongConstant")
    private boolean loginVerify() {
        name = login_username.getText() + "";
        password = login_password.getText() + "";
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入用户名", 1000).show();
            return false;

        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", 1000).show();
            return false;

        }
        if (!isMobileNO(name)) {
            Toast.makeText(this, "请输入有效的手机号码", 1000).show();

        }
        if (name.length() < 11) {
            Toast.makeText(this, "请输入11位合法手机号", 1000).show();
            return false;
        }
        if (password.length() < 4) {
            Toast.makeText(this, "请输入四位或以上密码", 1000).show();
            return false;
        }

        return true;
    }

    private void login() {
        RequestParams params = new RequestParams(AppConstant.URL + AppConstant.LOGIN_URL);
        params.addQueryStringParameter("mobile", name);
        params.addQueryStringParameter("password", password);
        JSONObject mjson = new JSONObject();

        try {
            mjson.put("mobile", name);
            mjson.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.setAsJsonContent(true);
        params.setBodyContent(mjson.toString());
        params.addHeader("Content-Type", "application/json");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @SuppressWarnings("WrongConstant")
            @Override
            public void onSuccess(String result) {
                LogUtil.i(result);
                login_loading.setVisibility(View.GONE);
                try {
                    JSONObject resultJson = new JSONObject(result);
                    if (resultJson.has("flag") && resultJson.getBoolean("flag")) {
                        Gson gson = new Gson();
                        if (resultJson.has("data")) {
                            JSONObject data = resultJson.getJSONObject("data");
                            JSONObject entity = data.getJSONObject("entity");
                            User user = gson.fromJson(entity.toString(), User.class);
                            AppConstant.user = user;
                            if (user != null && user.getId() != 0) {

                                editor = sharedPreferences.edit();//获取编辑器
                                editor.putString("mobile", user.getMobile());
                                editor.putInt("id", user.getId());
                                editor.putString("userNumber", user.getUserNumber());
                                editor.putString("userName", user.getUsername());
                                editor.putString("password", user.getPassword());
                                editor.commit();


                                if (isHomePage) {
                                    startActivity(new Intent(MainActivity.this, OldHomeActivity.class));

                                } else {
                                    startActivity(new Intent(MainActivity.this, Home2Activity.class));


                                }
                                finish();
                            }
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "用户名或密码错误,请重新输入", 1000).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                login_loading.setVisibility(View.GONE);
                LogUtil.e(ex.getMessage());
                Toast.makeText(MainActivity.this, ex.getMessage(), 1000).show();

            }

            @Override
            public void onCancelled(CancelledException cex) {
                login_loading.setVisibility(View.GONE);

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    private void upload() {
        if(!AppConstant.isHomePage) {
            auto();
            return;
        }
        RequestParams params = new RequestParams(AppConstant.URL + AppConstant.VERSION_GET_URL);
        params.addHeader("Content-Type", "application/json");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @SuppressWarnings("WrongConstant")
            @Override
            public void onSuccess(String result) {
                LogUtil.i(result);
                login_loading.setVisibility(View.GONE);
                try {
                    JSONObject resultJson = new JSONObject(result);
                    if (resultJson.has("flag") && resultJson.getBoolean("flag")) {
                        Gson gson = new Gson();
                        if (resultJson.has("data")) {
                            JSONObject data = resultJson.getJSONObject("data");
                            JSONObject entity = data.getJSONObject("entity");
                            VersionDataBean version = gson.fromJson(entity.toString(), VersionDataBean.class);
                            int serverVersionCode = 0;
                            try {
                                serverVersionCode = Integer.parseInt(version.getVercode());

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            int localVersionCode = getAppVersionName(MainActivity.this);
                            if (serverVersionCode > localVersionCode) {
//                            //服务器端版本号大于本地版本号,弹出dialog提示更新
//                            Message showUpdateDialog = Message.obtain();
//                            showUpdateDialog.what = SHOW_UPDATE_DIALOG;
//                            handler.sendMessage(showUpdateDialog);
                                showUpdateDialog(version.getAppurl(), version.getDescs());
                            }else{
                                auto();
                            }
                        }
//
//                        }
                    } else {
//                        Toast.makeText(MainActivity.this, "用户名或密码错误,请重新输入", 1000).show();
                        auto();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                login_loading.setVisibility(View.GONE);
                LogUtil.e(ex.getMessage());
                Toast.makeText(MainActivity.this, ex.getMessage(), 1000).show();
                auto();

            }

            @Override
            public void onCancelled(CancelledException cex) {
                login_loading.setVisibility(View.GONE);
                auto();

            }

            @Override
            public void onFinished() {

            }
        });

    }


    private static final String TAG = "SplashActivity";
    public static final int SHOW_UPDATE_DIALOG = 0;
    public static final int SHOW_ERROR = 1;
    public final static int CONNECT_TIMEOUT = 5000;
    public final static int READ_TIMEOUT = 5000;
    public final static int WRITE_TIMEOUT = 5000;

    //获取设备名称
    private String deviceName = Build.MODEL;
    //获取设备序列号
    private String serialNumber = getSerialNumber();
    private VersionDatas versionDataBean;


    /**
     * 弹出提示更新的dialog
     */
    private void showUpdateDialog(final String url, final String updateMsg) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setCancelable(false);
        dialog.setTitle("版本更新提示");
        dialog.setMessage("檢查到有最新版本,是否更新?");
        dialog.setNegativeButton("暫不更新,立即退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        dialog.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //从服务器端下载最新apk
                downloadApk(url);
            }
        });
        dialog.show();
    }

    /**
     * 从服务器端下载最新apk
     */
    private void downloadApk(String downUrl) {
        //显示下载进度
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        dialog.show();
        RequestParams requestParams = new RequestParams(AppConstant.URL + downUrl);
        requestParams.setSaveFilePath(AppConstant.BASE_PATH);
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                dialog.setMessage("下载中，请稍后……");
                dialog.setMax((int) total);
                dialog.setProgress((int) current);
            }

            @Override
            public void onSuccess(File result) {

                //下载完成,提示用户安装
                installApk(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                dialog.dismiss();
            }
        });
        //访问网络下载apk
//        new Thread(new DownloadApk(dialog)).start();
    }

    /**
     * 访问网络下载apk
     */
//    private class DownloadApk implements Runnable {
//        private ProgressDialog dialog;
//        InputStream is;
//        FileOutputStream fos;
//
//        public DownloadApk(ProgressDialog dialog) {
//            this.dialog = dialog;
//        }
//
//        @Override
//        public void run() {
//            OkHttpClient client = new OkHttpClient();
//            String url = versionDataBean.VERSION_URL;
//            Request request = new Request.Builder().get().url(url).build();
//            try {
//                Response response = client.newCall(request).execute();
//                if (response.isSuccessful()) {
//                    Log.d(TAG, "开始下载apk");
//                    //获取内容总长度
//                    long contentLength = response.body().contentLength();
//                    //设置最大值
//                    dialog.setMax((int) contentLength);
//                    //保存到sd卡
//                    File apkFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".apk");
//                    fos = new FileOutputStream(apkFile);
//                    //获得输入流
//                    is = response.body().byteStream();
//                    //定义缓冲区大小
//                    byte[] bys = new byte[1024];
//                    int progress = 0;
//                    int len = -1;
//                    while ((len = is.read(bys)) != -1) {
//                        try {
//                            Thread.sleep(1);
//                            fos.write(bys, 0, len);
//                            fos.flush();
//                            progress += len;
//                            //设置进度
//                            dialog.setProgress(progress);
//                        } catch (InterruptedException e) {
//                            Message msg = Message.obtain();
//                            msg.what = SHOW_ERROR;
//                            msg.obj = "ERROR:10002";
//                            handler.sendMessage(msg);
//                            load2Login();
//                        }
//                    }
//                    //下载完成,提示用户安装
//                    installApk(apkFile);
//                }
//            } catch (IOException e) {
//                Message msg = Message.obtain();
//                msg.what = SHOW_ERROR;
//                msg.obj = "ERROR:10003";
//                handler.sendMessage(msg);
//                load2Login();
//            } finally {
//                //关闭io流
//                if (is != null) {
//                    try {
//                        is.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    is = null;
//                }
//                if (fos != null) {
//                    try {
//                        fos.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    fos = null;
//                }
//            }
//            dialog.dismiss();
//        }
//    }

//    /**
//     * 下载完成,提示用户安装
//     */
    private void installApk(File file) {
        //调用系统安装程序
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivityForResult(intent, 300000);
    }


    /**
     * 获取设备序列号
     */
    private String getSerialNumber() {
        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
    }

    /**
     * 封装版本升级数据
     */
    private class VersionDatas {
        String COMMAND = "GET_APP_VERSION";
        String DEVICE_NAME = deviceName;
        String DEVICE_SN = serialNumber;
    }

    /**
     * 返回当前程序版本名
     */
    public static int getAppVersionName(Context context) {
        String versionName = "";
        int versioncode = 0;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            versioncode = pi.versionCode;
            if (versioncode < 1) {
                return -1;
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versioncode;
    }
}
